<?php
namespace app\home\controller;

use think\Db;
use app\api\model\ClassroomOrder as ClassroomOrderModel;//订单
use app\api\model\ActivityOrder as ActivityOrderModel;//捐赠
use app\api\model\Feedback as FeedbackModel;//意见反馈
use app\api\model\AboutUs as AboutUsModel;//关于我们
use app\api\model\InstitutionalActivities as InstitutionalActivitiesModel;
use EasyWeChat\Foundation\Application;
use think\Config;
use org\Qiniu;
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2018/9/4
 * Time: 10:08
 */
class My extends Common
{
    //我的首页
    public function index(){
        session('target_url',"http://south.xuanwumobile.com/home/My/index");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        $user_id = session('u_openid');
        $uid = ','.$user_id.',';
        $where['n_user_id'] = array('like',"%$uid%");
        $where['n_read_user'] = array('notlike',"%$uid%");
        $where['n_clear_user'] = array('notlike',"%$uid%");
        $where['n_status'] = 1;

        $count  = Db::table('up_notice')->where($where)->count();
        $res = Db::table('up_u_user')->where('user_id',$user_id)->field('user_image,user_username,user_me_content')->find();
        if($count > 99){
            $count = '99+';
        }
        $this->assign('count',$count);
        $this->assign('res',$res);
        return $this->fetch();
    }

    //   我的活动
    public function  my_huodong(){
        session('target_url',"http://south.xuanwumobile.com/home/My/my_huodong");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    /**
     *我的活动
     */
    public function myactivites(){
        $page = input('param.page')?input('param.page'):1;

        session('target_url',"http://south.xuanwumobile.com/home/My/myactivites?page".$page);
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        $user_id =session('u_openid');
        $num = $page-1;
        $where['delete_type'] = 1;
        $data = Db::table('up_institutional_activities_member')
            ->alias('a')
            ->join('up_institutional_activities uia','uia.id = a.institutional_activities_id','left')
            ->join('up_mechanism um','um.mechanism_id = uia.activity_mechanism_id','left')
            ->where('a.user_id',$user_id)
            ->where($where)
            ->field(
                'a.sign_status,
                    um.mechanism_name,
                    uia.activity_longitude,uia.activity_latitude,uia.id,
                    uia.activity_name,uia.activity_img,uia.activity_address,
                    uia.activity_start_time,uia.activity_end_time,uia.activity_status'
            )
            ->limit($num*10,10)
            ->select();
        return json(['status'=>200,'msg'=>$data]);
    }
    /***
     * 取消报名
     */
    public function cancelSign(){
        $user_id = session('u_openid');
        $InstitutionalActivitiesModel=new InstitutionalActivitiesModel();
        $id = input('param.id');//活动ID
        $where1['user_id'] = $user_id;
        $where1['institutional_activities_id'] = $id;
        //查询这个用户的报名这个活动
        $sign_status_info = Db::table('up_institutional_activities_member')->where($where1)->find();
        if(!$sign_status_info['id']){//证明没有报名，不能取消报名
            $this->apiError('E123');
        }
//        else{
//            if($sign_status_info['sign_status']==2){//已经签到不能取消报名
//                $this->apiError('E129');
//            }
//        }
        $now_time = time();//取消报名的现在时间
        $where['id'] = $id;
        $info = $InstitutionalActivitiesModel->getInfoList($where);//获取单条活动信息
        if($info['activity_status']==3){
            $this->apiError('E124');
        }
        if(strtotime($info['activity_sign_start'])>0&&strtotime($info['activity_sign_end'])>0){
            //设置活动报名的时间
            if(strtotime($info['activity_sign_start'])<$now_time
                &&$now_time <strtotime($info['activity_sign_end']))
            {//时间段之内
                $this->thisSign($user_id,$id);//取消报名

            }else{
//                if(strtotime($info['activity_sign_end'])<=strtotime($info['activity_start_time'])){//活动报名时间和活动开始时间相等
//                    $time = strtotime($info['activity_start_time'])-7200;//前2个小时
//                    if($time<$now_time&&$now_time<strtotime($info['activity_start_time'])){//在这个时间段里面不可以取消报名
                //不可以取消报名
                $this->apiError('E124');
//                    }else{
//                        //取消报名
//                        $this->thisSign($user_id,$id);
//                    }
//                }
            }
        }else{//没有设置活动报名时间
            if(strtotime($info['create_time'])<$now_time &&$now_time <strtotime($info['activity_end_time'])){
                //可以取消报名
                $this->thisSign($user_id,$id);
            }else{//不可以取消取消报名
                $this->apiError('E124');
            }
        }
    }

    /**
     * @param $user_id
     * @param $id
     * 取消报名
     */
    protected function thisSign($user_id,$id){
        $InstitutionalActivitiesModel=new InstitutionalActivitiesModel();
        $data['user_id'] = $user_id;
        $data['institutional_activities_id'] = $id;
        $member_id = Db::table('up_institutional_activities_member')->where($data)->value('id');//查询该用户是否已经报名
        if(!$member_id){
            $this->apiError('E123');
        }else{
            $res = $InstitutionalActivitiesModel->where('id',$id)->setDec('activity_num',1);//报名人数每次减1
            Db::table('up_institutional_activities_member')->where($data)->delete();//删除该用户报名

            if($res){
                $this->apiSuccess();
            }else{
                $this->apiError('K100');
            }
        }
    }
    /***
     * 删除我的活动
     */
    public function  deletemyActivies(){
//        extract(input());
        $user_id = session('u_openid');
        $id = input('param.id');
        $activity_status =Db::table('up_institutional_activities')->where('id',$id)->value('activity_status');
        if($activity_status!=4){
            $this->apiError('E136');
        }
        $where['user_id'] = $user_id;
        $where['institutional_activities_id'] = $id;
        $res = Db::table('up_institutional_activities_member')->where($where)->setField('delete_type',2);
        if($res){
            $this->apiSuccess();
        }else{
            $this->apiError('E001');
        }
    }

    //   我的课程
    public function  my_class(){
        session('target_url',"http://south.xuanwumobile.com/home/My/my_class");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    public function  my_class2(){
        session('target_url',"http://south.xuanwumobile.com/home/My/my_class2");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    /***
     * 我的课程收藏
     */
    public function myclasscollection(){
        $user_id = session('u_openid');
        $page = input('param.page')?input('param.page'):1;
        $num = $page-1;
        $res = Db::table('up_my_classroom')
            ->alias('a')
            ->join('up_classroom uc','uc.id = a.classroom_id','left')
            ->field('uc.classroom_title,uc.classroom_img, uc.classroom_cate, uc.classroom_price,a.*')
            ->where('a.user_id',$user_id)
            ->limit($num*10,10)
            ->select();
        return json(['status'=>200,'msg'=>$res]);
    }
    /***
     * 我的观看历史
     */
    public function histroyclass(){
        $user_id =session('u_openid');
        $page = input('param.page')?input('param.page'):1;
        $num = $page-1;
        $res = Db::table('up_classroom_history')
            ->alias('a')
            ->join('up_classroom uc','uc.id = a.classroom_id','left')
            ->field('uc.classroom_title, uc.classroom_img, uc.classroom_cate, uc.classroom_price, a.*')
            ->where('a.user_id',$user_id)
            ->limit($num*10,10)
            ->select();
        return json(['status'=>200,'msg'=>$res]);
    }


    /***
     * 删除我的课程收藏，观看历史
     */
    public function deletemyclass(){
        extract(input());
        $type = input('param.type');
        $id = input('param.id');
        $history_id = input('param.history_id');
        if($type==1){//删除收藏课程
            $res = Db::table('up_my_classroom')->where('id','IN',$id)->delete();
            if($res){
                $this->apiSuccess();
            }else{
                $this->apiError('E001');
            }
        }elseif ($type==2){//删除观看历史记录
            $res = Db::table('up_classroom_history')->where('history_id','IN',$history_id)->delete();
//            print_r($res);die;
            if($res){
                $this->apiSuccess();
            }else{
                $this->apiError('E001');
            }
        }

    }


//   我的问答
    public function  my_wenda(){
        session('target_url',"http://south.xuanwumobile.com/home/My/my_wenda");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    //   我的问答2
    public function  my_wenda2(){
        session('target_url',"http://south.xuanwumobile.com/home/My/my_wenda2");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }

    /**
     * 我的问答
     */
    public function myanswer()
    {
        $user_id = session('u_openid');
        $page = input('param.page') ? input('param.page') : 1;
        $type = input('param.type');
        $num = $page - 1;
        if ($type == 1) {
            $res = Db::table('up_interlocution')->where('user_id', $user_id)->limit($num * 10, 10)->select();
            foreach ($res as $key => &$vo) {
//                $aa = explode(',',trim($vo['interlocution_img'],','));
//                if(count(array_filter($aa))>0){
//                    $vv['interlocution_img'] = $aa;
//                }else{
//                    $vv['interlocution_img'] = array();
//                }
                $day = date('Y-m-d', time());//当前时间
                $time = time() - 3600 * 24;//昨天的时间戳
                $last_time = date('Y-m-d 00:00:00', $time);//昨天开始
                $last_time1 = date('Y-m-d 23:59:59', $time);//昨天结束
                if ($day == date('Y-m-d', strtotime($vo['interlocution_time']))) {//判断是否是今天
                    $vo['interlocution_time'] = date('H:i', strtotime($vo['interlocution_time']));
                } elseif ($last_time < $vo['interlocution_time'] && $vo['interlocution_time'] < $last_time1) {
                    //判断是否是昨天
                    $vo['interlocution_time'] = date('m-d', strtotime($vo['interlocution_time']));
                } else {
                    $vo['interlocution_time'] = date('Y-m-d', strtotime($vo['interlocution_time']));
                }
            }
        } else {
            $res = Db::table('up_interlocution_answer')
                ->alias('a')
                ->join('up_interlocution ui', 'ui.interlocution_id = a.f_interlocution_id', 'left')
                ->where('a.user_id', $user_id)
                ->field('a.*,ui.interlocution_title')
                ->limit($num * 10, 10)
                ->select();
            foreach ($res as $key => &$vo) {
//                $aa = explode(',',trim($vo['answer_img'],','));
//                if(count(array_filter($aa))>0){
//                    $vv['answer_img'] = $aa;
//                }else{
//                    $vv['answer_img'] = array();
//                }
                $day = date('Y-m-d', time());//当前时间
                $time = time() - 3600 * 24;//昨天的时间戳
                $last_time = date('Y-m-d 00:00:00', $time);//昨天开始
                $last_time1 = date('Y-m-d 23:59:59', $time);//昨天结束
                if ($day == date('Y-m-d', strtotime($vo['answer_time']))) {//判断是否是今天
                    $vo['answer_time'] = date('H:i', strtotime($vo['answer_time']));
                } elseif ($last_time < $vo['answer_time'] && $vo['answer_time'] < $last_time1) {
                    //判断是否是昨天
                    $vo['answer_time'] = date('m-d', strtotime($vo['answer_time']));
                } else {
                    $vo['answer_time'] = date('Y-m-d', strtotime($vo['answer_time']));
                }

            }
        }
        return json(['status'=>200,'msg'=>$res]);
    }



    // 我的收藏
    public function  shouce(){
        session('target_url',"http://south.xuanwumobile.com/home/My/shouce");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    // 我的收藏2
    public function  shouce2(){
        session('target_url',"http://south.xuanwumobile.com/home/My/shouce2");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }

    /**
     * 我的收藏
     * type：类型   1资讯   2活动
     * page：当前页码  默认1
     */
    public function myCollect()
    {
        //TODO:user_id
        $user_id = session('u_openid');
        extract(input());
//        print_r(input('param.'));die;
        if($type == 1) {//收藏资讯
            $data = Db::table('up_my_collection')->alias('umc')
                ->join('up_information i', 'i.information_id = umc.information_id', 'left')
                ->join('up_mechanism m', 'i.mechanism_id = m.mechanism_id', 'left')
                ->where('umc.user_id', $user_id)
                ->field('i.information_id,i.information_title,i.information_content,
                i.information_img,i.information_introduce,i.information_release_time,
                m.mechanism_id,m.mechanism_name, umc.collection_id as collect_id')
                ->page($page, 10)
                ->select();
        } elseif($type == 2) {//收藏的活动
            $data = Db::table('up_my_activities')->alias('uma')
                ->join('up_institutional_activities ia', 'ia.id = uma.institutional_activities_id', 'left')
                ->where('uma.user_id', $user_id)
                ->where('ia.is_show', 1)
                ->field('ia.id,ia.activity_name,ia.activity_address,ia.activity_img, uma.id as collect_id, 
                 ia.activity_start_time,ia.activity_end_time,ia.activity_status,ia.activity_id')
                ->page($page, 10)
                ->select();
            foreach($data as $k => &$v) {
                $activity_name = Db::table('up_activity')->where('id', 'IN', trim($v['activity_id'], ','))->column('activity_name');
                $v['activity_type_name'] = implode(',', $activity_name);

                $time_Y = date('Y');//当前的年
                $start_time = strtotime($v['activity_start_time']);
                $start_Y = date('Y', $start_time);//活动开始的年
                $start_m = date('m', $start_time);//活动开始的月
                $start_d = date('d', $start_time);//活动开始的日
                $start_Hi = date('H:i', $start_time);//活动开始的时分
                $end_time = strtotime($v['activity_end_time']);
                $end_Y = date('Y', $end_time);//活动结束的年
                $end_m = date('m', $end_time);//活动结束的月
                $end_d = date('d', $end_time);//活动结束的日
                $end_Hi = date('H:i', $end_time);//活动结束的时分
                if($time_Y == $start_Y && $time_Y == $end_Y) {//今年
                    if($start_m == $end_m && $start_d == $end_d) {//不跨天
                        $v['activity_start_time'] = $start_m . '-' . $start_d . ' ' . $start_Hi;
                        $v['activity_end_time'] = $end_Hi;
                    } else {//跨天
                        $v['activity_start_time'] = $start_m . '-' . $start_d . ' ' . $start_Hi;
                        $v['activity_end_time'] = $end_m . '-' . $end_d . ' ' . $end_Hi;
                    }
                } else {//不同年
                    if($start_m == $end_m && $start_d == $end_d) {//不跨天
                        $v['activity_start_time'] = $start_Y . '-' . $start_m . '-' . $start_d . ' ' . $start_Hi;
                        $v['activity_end_time'] = $end_m . '-' . $end_d . ' ' . $end_Hi;
                    } else {//跨天
                        $v['activity_start_time'] = $start_Y . '-' . $start_m . '-' . $start_d . ' ' . $start_Hi;
                        $v['activity_end_time'] = $end_Y . '-' . $end_m . '-' . $end_d . ' ' . $end_Hi;
                    }
                }
            }
        }
        $this->apiSuccess($data);
    }

    /**
     * 删除我收藏的资讯、活动
     * type：删除的类型  1 资讯  2 活动
     * ids：需要删除的记录   如1,2,3的形式
     */
    public function delCollect()
    {
        $parms = input('param.');
        $ids = explode(',', $parms['ids']);
        if($parms['type'] == 1) {//删除资讯
            $res = Db::table('up_my_collection')
                ->where('collection_id', 'in', $ids)
                ->delete();
        } else {//删除活动
            $res = Db::table('up_my_activities')
                ->where('id', 'IN', $ids)
                ->delete();
        }
        if($res) {
            return $this->apiSuccess();
        } else {
            return $this->apiError('E001');
        }
    }





    // 我的订单
    public function  myorder(){
        session('target_url',"http://south.xuanwumobile.com/home/My/myorder");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    //我的订单详情
    public function  myorder_detail(){
        session('target_url',"http://south.xuanwumobile.com/home/My/myorder_detail");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }

    /**
     * 我的订单列表
     * page：当前页码
     */
    public function myOrderList()
    {
        $page = input('param.page')?input('param.page'):1;
        $user_id = session('u_openid');
        $where = [
            'o.user_id' => $user_id,//本用户
            'o.order_status' => 1,//已完成
        ];
        $field = 'uc.classroom_img, uc.classroom_title, o.pay_time, o.order_id, o.order_status';
        $classroomOrderModel = new ClassroomOrderModel();
        $lists = $classroomOrderModel->myOrderList($where, '', $field, $page);
        foreach($lists as &$list) {
            $list['pay_time'] = substr($list['pay_time'], 0, 10);
        }
//        return $this->apiSuccess($lists);
        return json(['status'=>200,'msg'=>$lists]);

    }

    /**
     * 订单详情
     * order_id：订单ID
     */
    public function orderInfo()
    {
        $order_id = input('param.order_id');
        $where['o.order_id'] = $order_id;
        $field = 'o.order_id, o.order_money, o.order_type, o.order_number, o.order_time, o.pay_time,
        uc.classroom_img, uc.classroom_title';
        $classroomOrderModel = new ClassroomOrderModel();
        $orderInfo = $classroomOrderModel->myOrderList($where, $order_id, $field, '');
        return $this->apiSuccess($orderInfo);
    }

    /**
     * 删除订单
     * order_id：订单ID
     */
    public function delOrder()
    {
        $params = input('param.');
        $classroomOrderModel = new ClassroomOrderModel();
        $res = $classroomOrderModel->delOrder($params['order_id']);
        if($res) {
            return $this->apiSuccess();
        } else {
            return $this->apiError('E001');
        }
    }


    //   我的捐赠记录donation_recordlist_detail
    public function  donation_recordlist(){
        session('target_url',"http://south.xuanwumobile.com/home/My/donation_recordlist");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    //   我的捐赠记录的详情person_center
    public function  donation_recordlist_detail(){
        session('target_url',"http://south.xuanwumobile.com/home/My/donation_recordlist_detail");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    /**
     * 捐赠列表
     * page：当前页码
     */
    public function donateList()
    {
        $user_id = session('u_openid');
        $page = input('param.page')?input('param.page'):1;
        $activityOrderModel = new ActivityOrderModel();
        $where = [
            'user_id' => $user_id,//本用户
            'donate_status' => 1,//已完成
        ];
        $field = 'donate_id, pay_time, cate';
        $lists = $activityOrderModel->donateList($where, '', $field, $page);
        foreach($lists as &$list) {
            $list['pay_time'] = substr($list['pay_time'], 0, -3);
        }
        return json(['status'=>200,'msg'=>$lists]);

//        return $this->apiSuccess($lists);
    }

    /**
     * 订单详情
     * donate_id：捐赠记录ID
     */
    public function donateInfo()
    {
        $params = input('param.');
        $where['d.donate_id'] = $params['donate_id'];
        $field = 'd.donate_id, d.donate_money, d.pay_time, d.donate_type, d.donate_number, uia.activity_name';
        $activityOrderModel = new ActivityOrderModel();
        $donateInfo = $activityOrderModel->donateList($where, $params['donate_id'], $field, '');
        return $this->apiSuccess($donateInfo);
    }


    /**
     * 用户信息
     */
    public function getUserData()
    {
        extract(input());
        $user_id = session('u_openid');
        $data = Db::table('up_u_user u')
            ->join('up_area a', 'a.district_id = u.user_shi', 'left')
            ->where('user_id', $user_id)
            ->field('u.user_attestation,u.user_username,u.user_image,u.user_age,a.district,u.user_me_content,u.user_attestation')
            ->find();

        $this->apiSuccess($data);
    }

    /**
     * 用户认证信息回显
     */
    public function getUserList()
    {
        $user_id=session('u_openid');
        extract(input());
        $data = Db::table('up_u_user u')
            ->join('up_area a', 'a.district_id = u.user_shi', 'left')
            ->join('up_assortment ua1', 'ua1.assortment_id = u.user_hospital', 'left')
            ->join('up_assortment ua2', 'ua2.assortment_id = u.user_department', 'left')
            ->join('up_assortment ua3', 'ua3.assortment_id = u.user_title', 'left')
            ->join('up_assortment ua4', 'ua4.assortment_id = u.user_post', 'left')
            ->join('up_mechanism um', 'um.mechanism_id = u.user_to_mechanism_id', 'left')
            ->where('user_id', $user_id)
            ->field('u.user_attestation,u.user_username,
            u.user_image,u.user_age,a.district,a.district_id,
            u.user_me_content,u.user_attestation,u.user_card,u.user_rel_name,
            ua1.assortment_name as hospital,ua2.assortment_name as department,
            ua3.assortment_name as title,ua4.assortment_name as post,u.user_business_image,
            um.mechanism_id,um.mechanism_name,u.user_hospital,u.user_department,u.user_title,u.user_post')
            ->find();
        $data['user_business_image'] = explode(',',trim($data['user_business_image'],','));
        $rrr = Db::table('up_u_user')->where('user_id',$user_id)->value('user_business_image');
        $data['img'] = trim($rrr,',');
        $this->apiSuccess($data);
    }

    /**
     * 修改用户信息
     * @throws \think\Exception
     * name:用户姓名
     * image：头像
     * age：年龄
     * district_id：城市ID
     * content：介绍
     */
    public function editUser()
    {
        extract(input());
        $user_id =session('u_openid');
        $param = [];
        if(isset($name)) {
            $param['user_username'] = $name;
        }
        if(isset($user_image)) {
            $up = new Qiniu();
            $img = base64_img1($user_image)['msg'];
            //取出图片后缀
            $type = explode(".",$img);
            $type = end($type);
            //组装图片名
            $key = md5(time().uuid()).'.'.$type;
            $arr = $up->uploadFile($img,$key,'http://qiniu.verynurse.com/');
            unlink($img);
            $param['user_image'] = $arr;
        }
        if(isset($user_age)) {
            $param['user_age'] = $user_age;
        }
        if(isset($district_id)) {
            $param['user_shi'] = $district_id;
        }
        if(isset($content)) {
            $param['user_me_content'] = $content;
        }
        $param['user_update_time'] = date('Y-m-d H:i:s');
        //TODO:user_id

        $res = Db::table('up_u_user')->where('user_id', $user_id)->update($param);
        if($res) {
            $this->apiSuccess();
        } else {
            $this->apiError(100, '修改失败');
        }
    }



    /**
     * 志愿者认证  第一步
     * name 姓名
     * card 身份证号
     * mechanism_id 机构id
     * shi 市id
     */
    public function approveFirst()
    {
        extract(input());

        $param =array();
        $user_id =session('u_openid');
        if($name!=''){
            $param['user_rel_name'] = $name;
        }
        if($card!=''){
            $param['user_card'] = $card;
        }
        if($mechanism_id!=''){
            $param['user_to_mechanism_id'] = $mechanism_id;
        }
        if($shi!=''){
            $param['user_shi'] = $shi;
        }
        Db::table('up_u_user')->where('user_id', $user_id)->update($param);
        $this->apiSuccess('提交成功');

    }

    /**
     * 志愿者认证 第二步
     * hospital 医院id
     * department 科室id
     * title 职称
     * duty 职务
     * business 证件照
     */
    public function approveSecond()
    {

        extract(input());
        $user_id = session('u_openid');
        $param = array();
        if($hospital != ''){
            $param['user_hospital'] = $hospital;
        }
        if($department != ''){
            $param['user_department'] = $department;
        }

        if($title != ''){
            $param['user_title'] = $title;
        }

        if($duty != ''){
            $param['user_post'] = $duty;
        }

        $up = new Qiniu();
        if(isset($business)){
            foreach($business as $key=>$vo){
                $img1 = base64_img1 ($vo)['msg'];
                //取出图片后缀
                $type = explode(".",$img1);
                $type = end($type);
                //组装图片名
                $key = md5(time().uuid()).'.'.$type;
                $arr[] = $up->uploadFile($img1,$key,'http://qiniu.verynurse.com/');
                unlink($img1);
            }
            $param['user_business_image'] = implode (',',$arr).',';
        }

        if($param['user_business_image']==''){
            $param['user_business_image'] = $image;
        }else{
            $param['user_business_image'] = $param['user_business_image'].$image.',';
        }

        $param['user_attestation'] = 2;
        $param['user_join_time'] = date('Y-m-d H:i:s');
        Db::table('up_u_user')->where('user_id', $user_id)->update($param);
        $this->apiSuccess('提交成功');

    }

    /**
     * 志愿者认证时返回上一步
     */
    public function approvBack(){
        $user_id =session('u_openid');
        $res = Db::table('up_u_user')->alias('uuu')
            ->join('up_area ua', 'ua.district_id = uuu.user_shi', 'left')
            ->join('up_mechanism um', 'um.mechanism_id = uuu.user_to_mechanism_id', 'left')
            ->field('uuu.user_rel_name, uuu.user_card, uuu.user_to_mechanism_id, 
            ua.district_id, ua.district, um.mechanism_name')
            ->where('uuu.user_id',$user_id)
            ->find();
        return $this->apiSuccess($res);
    }

    /**
     * 志愿者认证回显第二步
     */
    public function approvSec(){
        $user_id =session('u_openid');
        $res = Db::table('up_u_user')->alias('uuu')
            ->join('up_assortment ua1', 'ua1.assortment_id = uuu.user_hospital', 'left')
            ->join('up_assortment ua2', 'ua2.assortment_id = uuu.user_department', 'left')
            ->join('up_assortment ua3', 'ua3.assortment_id = uuu.user_title', 'left')
            ->join('up_assortment ua4', 'ua4.assortment_id = uuu.user_post', 'left')
            ->field('ua1.assortment_name as hospital, ua1.assortment_id as hospital_id, 
            ua2.assortment_name as department, ua2.assortment_id as department_id, 
            ua3.assortment_name as title, ua3.assortment_id as title_id,
            ua4.assortment_name as post, ua4.assortment_id as post_id, uuu.user_business_image')
            ->where('uuu.user_id', $user_id)
            ->find();
        $img = explode(',', trim($res['user_business_image'], ','));
        if(empty($img)){
            $res['user_business_image'] = [];
        }else{
            $res['user_business_image'] = $img;
        }
        return $this->apiSuccess($res);
    }

    /**
     * 获取机构 & 搜索机构
     * key：搜索关键字
     */
    public function getMechanism()
    {
        extract(input());
        $map['mechanism_status'] = 2;
        $map['mechanism_id'] = ['neq', 1];
        if($key != "") {
            $map['mechanism_name'] = ['like', "%" . $key . "%"];
        }
        $data = Db::table('up_mechanism')
            ->where($map)
            ->field('mechanism_id,mechanism_code,mechanism_name as name,mechanism_logo')
            ->select();
        $this->apiSuccess($data);
    }

    /**
     * 获取医院 科室、职务、职称数据 & 搜索
     * type：1医院 2科室 3职称 4职务
     * key：搜索关键字
     */
    public function getHospital()
    {
        extract(input());
        $map['assortment_type'] = $type;
        if($key != "") {
            $map['assortment_name'] = ['like', "%" . $key . "%"];
        }
        $data = Db::table('up_assortment')
            ->where($map)
            ->field('assortment_id,assortment_name as name')
            ->select();
        $this->apiSuccess($data);
    }



    /**
     * 意见反馈
     * content：反馈内容
     */
    public function createFeedback()
    {
        $user_id = session('u_openid');
        $params = input('param.');
        $content = trim($params['content'], ' ');
        if(empty($content)) {
            return $this->apiError(4006);
        }
        $num = mb_strlen($content, 'utf8');
        if($num > 200) {
            return $this->apiError(4008);
        }
        $data = [
            'user_id' => $user_id,//用户ID
            'feedback_content' => $content,//反馈内容
            'feedback_time' => date('Y-m-d H:i:s'),//反馈时间
        ];
        $feedbackModel = new FeedbackModel();
        $res = $feedbackModel->createFeedback($data);
        if($res) {
            return $this->apiSuccess();
        } else {
            return $this->apiError('E000');
        }
    }

    /**
     * 关于我们
     */
    public function aboutUs()
    {
        $aboutUsModel = new AboutUsModel();
        $field = 'about_us';
        $content = $aboutUsModel->getField($field);
        return $this->apiSuccess($content);
    }

    /**
     * 打赏捐款好处
     */
    public function donateBenefit()
    {
        $aboutUsModel = new AboutUsModel();
        $field = 'donate_benefit';
        $content = $aboutUsModel->getField($field);
        return $this->apiSuccess($content);
    }

    /**
     * 用户协议
     */
    public function userArgement()
    {
        $aboutUsModel = new AboutUsModel();
        $field = 'user_argement';
        $content = $aboutUsModel->getField($field);
        return $this->apiSuccess($content);
    }

    /**
     * 收费功能开关
     */
    public function ifPrice()
    {
        $aboutUsModel = new AboutUsModel();
        $field = 'price_button';
        $content = $aboutUsModel->getField($field);
        return $this->apiSuccess($content);
    }

    /**
     * 获取省市数组
     */
    public function getArea()
    {
        $shengLists = Db::name('area')->field('district_id, district')->where('level', 1)->select();
        $shiLists = Db::name('area')->field('district_id, district, pid')->where('level', 2)->select();
        foreach($shengLists as $key => $shengList) {
            for($i = 0; $i < count($shiLists); $i++) {
                if($shiLists[$i]['pid'] == $shengList['district_id']) {
                    $shengLists[$key]['shi'][] = $shiLists[$i];
                }
            }
        }
        return $this->apiSuccess($shengLists);
    }

    /**
     * 获取热门城市
     */
    public function getHotArea()
    {
        //热门城市ID
        $hotArea = [
            1002,//北京市
            1020,//上海市
            1832,//广州市
            1834,//深圳市
            2965,//成都市
            1038,//天津市
            1182,//苏州市
            1730,//杭州市
            1178,//南京市
            1848,//东莞市
            1288,//武汉市
            1179,//无锡市
            1731,//宁波市
            2326,//福州市
            2810//济南市
        ];
        $hotArea = Db::table('up_area')
            ->field('district_id, district')
            ->where('district_id', 'IN', $hotArea)
            ->select();
        return $this->apiSuccess($hotArea);
    }

    /****
     * 公益历程，我的荣誉证书
     */
    public function myhonor(){
        extract(input());
        $user_id =session('u_openid');
        $page = input('param.page')?input('param.page'):1;
        $num = $page -1;
        $uid = ','.$user_id.',';
        $where['user_id'] = array('like',"%$uid%");
        $res = Db::table('up_my_welfare')->where($where)->field('welfare_id,welfare_title,create_time')->limit($num*10,10)->select();
        $this->apiSuccess($res);
    }

    /***
     * 荣誉证书详情
     */
    public function honordetail(){
        $welfare_id = input('param.welfare_id');
        $res = Db::table('up_my_welfare')->where('welfare_id',$welfare_id)->find();
        $this->apiSuccess($res);
    }
    /**
     * 我的证书
     */
    public function certificate(){
        extract(input());
        //用户信息
        $user_id =session('u_openid');
        $user_info =Db::table('up_u_user')
            ->alias('a')
            ->join('up_mechanism um','um.mechanism_id = a.user_to_mechanism_id','left')
            ->where('a.user_id',$user_id)
            ->field('a.user_sh_time,a.user_id,a.user_sh_time,a.user_username,a.user_gender,
     um.mechanism_name,a.user_join_time,a.user_number')
            ->find();
        $this->apiSuccess($user_info);

    }










//   公益历程1
    public function  gongyilicheng(){
        session('target_url',"http://south.xuanwumobile.com/home/My/gongyilicheng");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    //   公益历程2
    public function  gongyilicheng2(){
        session('target_url',"http://south.xuanwumobile.com/home/My/gongyilicheng2");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    //   公益历程2之详情
    public function  gongyilicheng_detail(){
        session('target_url',"http://south.xuanwumobile.com/home/My/gongyilicheng_detail");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    //   志愿者认证之身份认证
    public function  zhiyuanzhe_renzheng1(){
        session('target_url',"http://south.xuanwumobile.com/home/My/zhiyuanzhe_renzheng1");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    //   志愿者认证之职业认证
    public function  zhiyuanzhe_renzheng2(){
        session('target_url',"http://south.xuanwumobile.com/home/My/zhiyuanzhe_renzheng2");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        //-----------------获取微信位置接口-----------------------
        $options = Config::get('wechat');
        $app = new Application($options);
        $js = $app->js;
        $json = $js->config(array('getLocation','chooseImage','uploadImage','downloadImage','getLocalImgData'), false ,false,true);
        $this->assign(['json'=>$json]);
        return  $this->fetch();
    }
    //   志愿者认证之认证等待
    public function  renzheng_waitting(){
        session('target_url',"http://south.xuanwumobile.com/home/My/renzheng_waitting");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    //   志愿者认证之认证失败
    public function  renzheng_fail(){
        session('target_url',"http://south.xuanwumobile.com/home/My/renzheng_fail");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    //   志愿者认证之认证成功
    public function  renzheng_success(){
        session('target_url',"http://south.xuanwumobile.com/home/My/renzheng_success");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    //   志愿者认证之认证成功之后的详情
    public function  renzheng_information(){
        session('target_url',"http://south.xuanwumobile.com/home/My/renzheng_information");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    //   志愿者认证之选择机构
    public function  select_jigou(){
        session('target_url',"http://south.xuanwumobile.com/home/My/select_jigou");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    //   志愿者认证之选择科室
    public function  select_keshi(){
        session('target_url',"http://south.xuanwumobile.com/home/My/select_keshi");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    //   志愿者认证之选择职称
    public function  select_zhicheng(){
        session('target_url',"http://south.xuanwumobile.com/home/My/select_zhicheng");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    //   志愿者认证之选择职务
    public function  select_zhiwu(){
        session('target_url',"http://south.xuanwumobile.com/home/My/select_zhiwu");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    public function  select_area2(){
        session('target_url',"http://south.xuanwumobile.com/home/My/select_area2");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        //-----------------获取微信位置接口-----------------------
        $options = Config::get('wechat');
        $app = new Application($options);
        $js = $app->js;
        $json = $js->config(array('getLocation','chooseImage','uploadImage','downloadImage','getLocalImgData'), false ,false,true);
        $this->assign(['json'=>$json]);
        return  $this->fetch();
    }
    //   志愿者认证之选择区域
    public function  select_area(){
        session('target_url',"http://south.xuanwumobile.com/home/My/select_area");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        //-----------------获取微信位置接口-----------------------
        $options = Config::get('wechat');
        $app = new Application($options);
        $js = $app->js;
        $json = $js->config(array('getLocation','chooseImage','uploadImage','downloadImage','getLocalImgData'), false ,false,true);
        $this->assign(['json'=>$json]);
        return  $this->fetch();
    }
    //   志愿者认证之选择医院
    public function  select_hospital(){
        session('target_url',"http://south.xuanwumobile.com/home/My/select_hospital");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    //   志愿者认证之选择年龄
    public function  select_age(){
        session('target_url',"http://south.xuanwumobile.com/home/My/select_age");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }


    //   我的个人中心
    public function  person_center(){
        session('target_url',"http://south.xuanwumobile.com/home/My/person_center");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        //-----------------获取微信位置接口-----------------------
        $options = Config::get('wechat');
        $app = new Application($options);
        $js = $app->js;
        $json = $js->config(array('getLocation','chooseImage','uploadImage','downloadImage','getLocalImgData'), false ,false,true);
        $this->assign(['json'=>$json]);
        return  $this->fetch();
    }
    //   我的个人中心之修改昵称
    public function  change_name(){
        session('target_url',"http://south.xuanwumobile.com/home/My/change_name");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    //   我的个人中心之修改介绍
    public function  change_jieshao(){
        session('target_url',"http://south.xuanwumobile.com/home/My/change_jieshao");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }


    //   我的问答详情wenda_huida
    public function  wenda_detail(){
        session('target_url',"http://south.xuanwumobile.com/home/My/wenda_detail");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    //   我的问答详情之操作（编辑删除和取消）
    public function  wenda_detail_operation(){
        session('target_url',"http://south.xuanwumobile.com/home/My/wenda_detail_operation");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    //   我的问答详情之回复
    public function  wenda_huida(){
        session('target_url',"http://south.xuanwumobile.com/home/My/wenda_huida");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    //   我的信息列表
    public function  my_xinxi(){
        session('target_url',"http://south.xuanwumobile.com/home/My/my_xinxi");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    //   我的某条信息详情
    public function  my_xinxi_detail(){
        session('target_url',"http://south.xuanwumobile.com/home/My/my_xinxi_detail");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    //   打赏记录
    public function ward_record(){
        session('target_url',"http://south.xuanwumobile.com/home/My/ward_record");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    //   我要捐赠
    public function go_donation(){
        session('target_url',"http://south.xuanwumobile.com/home/My/go_donation");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    //   设置
    public function shezhi(){
        session('target_url',"http://south.xuanwumobile.com/home/My/shezhi");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    //   设置之版本更新
    public function version_change(){
        session('target_url',"http://south.xuanwumobile.com/home/My/version_change");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    //   设置之关于我们
    public function about_we(){
        session('target_url',"http://south.xuanwumobile.com/home/My/about_we");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    //   设置之意见反馈
    public function  yijianfankui(){
        session('target_url',"http://south.xuanwumobile.com/home/My/yijianfankui");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    // 获取头像
    public function getheaderpicuter(){
        session('target_url',"http://south.xuanwumobile.com/home/My/getheaderpicuter");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return  $this->fetch();
    }
    public function myphone(){
//        session('target_url',"http://south.xuanwumobile.com/home/My/myphone");
//        $openid = $this->getOpenid();
//        $this->getUserId($openid);
        return $this->fetch();
    }
    /**
     * 发送验证码
     * @return \think\response\Json|void
     * phone：填写的手机号
     * type：   1 验证手机号   2 更换绑定的手机号
     */
    public function getPhoneCode(){
        header("Access-Control-Allow-Origin:*");
        $user_id = session('u_openid');
        $params = input('param.');
        if(trim($params['phone'], ' ') == ''){
            return $this->apiError(0, '请输入手机号');
        }
        if(!preg_match("/^1[3456789]\d{9}$/", $params['phone'])){
            return $this->apiError(1, '请输入正确格式的手机号');
        }

        $startTime = strtotime(date('Y-m-d 00:00:00'));//当天的起始时间
        $endTime = strtotime(date('Y-m-d 23:59:59'));//当天的结束时间
        $where = [];
        $where['phone'] = $params['phone'];
        $where['time2'] = ['between', [$startTime, $endTime]];
        $num = Db::table('up_phonecode')->where($where)->count('id');
        if($num == 5){
            return $this->apiError(10, '短信验证码今日已发送5次，请明天再来');
        }
        $code = GetRandCode();//6位数验证码
        $templateid = config('yzx')['templateid'];
        $sendres = YzxSms($templateid, $code, $params['phone'], $user_id);//发送验证码
        if($sendres['code'] != '00000'){//发送不成功
            return json(['status'=>11,'msg'=>$sendres['msg']]);
        }else{
            $data = [
                'phone' => $params['phone'],//发送的手机号
                'code' => $code,//加密后的验证码
                'time2' => time(),//验证码发送的时间戳
            ];
            $res = Db::table('up_phonecode')->insert($data);
            if(!$res){
                return json(['status' => 12, 'msg' => '数据库操作失败']);
            }
            return json(['status' => 200, 'msg' => $code]);
        }
    }

    /**
     * 更换手机号，第二部绑定新手机
     * @return string
     */
    public function ajaxBandPhone(){
        $phone = trim($_POST['phone'],' ');
        $code = trim($_POST['code'],' ');
        $user_id = session('u_openid');
        if($phone == "" || $code == ""){
            return json(['status'=>0,'msg'=>'手机号和验证码不能为空']);
        }
        //=============================================================
        $res = Db::table('up_phonecode')
            ->where('phone',$phone)
            ->order('time2 desc')
            ->limit(1)
            ->find();
        //=============================================================
        if(empty($res)){
            return json(['status'=>0,'msg'=>'不是同一个手机号']);
        }
        if($code != $res['code']){
            return json(['status'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 901){
            return json(['status'=>22,'msg'=>'验证码超时']);
        }
        if($res['status']==1){
            return json(['status'=>23,'msg'=>'验证码已使用']);
        }
        $res2 = Db::table('up_u_user')->where('user_id',$user_id)->update(['user_phone'=>$phone]);
        if($res2){
            return json(['status'=>200]);
        }else{
            return json(['status'=>0,'msg'=>'更新失败']);
        }
    }
    
    /**
     * 认证审核成功/失败原因
     * user_id:用户ID
     */
    public function falseReason(){
        $user_id = session('u_openid');
        $false_reason = Db::table('up_u_user')
            ->field('user_false_reason')
            ->where('user_id', $user_id)
            ->find();
        return $this->apiSuccess($false_reason);
    }
}